package org.client.chat;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;

import org.model.ChatStrings;
import org.secure.SecureInputStream;
import org.secure.SecureOutputStream;

public class ServerChatingWindow extends ChatingWindow implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private SecureOutputStream outputStream;
	private SecureInputStream inputStream;
	private Socket currentSocket;
	private String friendName;
	private boolean isRecieving = false;
	private String loginName;
	public ServerChatingWindow(Socket tempSocket,String loginName, byte[] key)
	{
		super("");
		this.loginName = loginName;
		sendButton.addActionListener(this);
		try {
			
			outputStream = new SecureOutputStream(tempSocket.getOutputStream());
			inputStream = new SecureInputStream(new InputStreamReader(tempSocket.getInputStream()));
			outputStream.setPrivateKey(key);
			inputStream.setPrivateKey(key);
			outputStream.setClient(false);
			inputStream.setClient(false);
			friendName = inputStream.readLine();
			setTitle(friendName);
			currentSocket = tempSocket; 
			new ChatListener(inputStream).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private class ChatListener extends Thread
	{
		private BufferedReader inputStream;
		public ChatListener(BufferedReader is)
		{
			inputStream =is;
		}
		@Override
		public void run() {
			super.run();
			try {
				while(true)
				{
					
					String line = inputStream.readLine();
					if(checkIfEndChat(line))
						break;
					if(!isRecieving)
					{
						chatArea.append(friendName+ChatStrings.USER_NEXT+line+"\n");
						isRecieving = true;
					}else
						chatArea.append(ChatStrings.SAPCES+line+"\n");
					chatArea.setCaretPosition(chatArea.getText().length());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	@Override
	public void actionPerformed(ActionEvent arg0) {
		try {
			
			String  line = sendField.getText();
			if(line == null || line.compareTo("") == 0)
				return;
			if(isRecieving)
			{
				chatArea.append(loginName+ChatStrings.USER_NEXT+line+"\n");
				isRecieving = false;
			}
			else
				chatArea.append(ChatStrings.SAPCES+line+"\n");
			chatArea.setCaretPosition(chatArea.getText().length());
			
			outputStream.writeString(line+ChatStrings.END_LINE);	
		} catch (Exception e) {
			//e.printStackTrace();
			System.err.print("partner is closed");
		}
	}
	@Override
	public void windowClosing(WindowEvent e) {
		try {
			byte[] end = new byte[3];
			end[0] = 1;
			end[1] = 2;
			end[2] = 3;
			String bytes = new String(end);
			outputStream.writeString(bytes+ChatStrings.END_LINE);
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}
}
